<?php

namespace App\Http\Controllers\Api;

use App\Bid_Order;
use App\Goods_Order;
use App\Http\Controllers\Controller;
use Faker\Generator as Faker;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    /**
     * 订单模块Api功能需求：
     * 1、新建并返回订单
     * 2、按用户id检索普通订单和拍卖订单 （买家身份）
     * 3、按匠人id检索普通订单和拍卖订单 （卖家身份）
     * 4、删除订单
     */
    public function index(Request $request)
    {
        if ($request->uid) { // 买家检索
            if ($request->type == 'goods') {
                return Goods_Order::where('buyer_id', $request->uid)->get();
            }else
            return Bid_Order::where('buyer_id', $request->uid)->get();

        } elseif ($request->cid) { // 卖家检索
            if ($request->type == 'goods') {
                return Goods_Order::where('seller_id', $request->cid)->get();
            }
            return Bid_Order::where('seller_id', $request->cid)->get();
        } else {
            abort(403);
        }
    }

    public function create(Request $request, Faker $faker)
    {
        return Goods_Order::create([
            'order_id' => $faker->ean13,
            'item_id' => $request->item_id,
            'buyer_id' => $request->buyer_id,
            'seller_id' => $request->seller_id,
            'amount' => $request->amount,
            'order_time' => now(),
            'remark' => $request->remark,
        ]);
    }

    public function showGoodsOrder($order_id)
    {
        return Goods_Order::where('order_id',$order_id)->with(['goods','seller:id,shop_name','buyer'])->firstOrFail();
    }

    public function pay($order_id)
    {
        Goods_Order::where('order_id',$order_id)->update([
            'status' => 1,
            'pay_time' => now()
        ]);
    }

    public function delGoodsOrder(Goods_Order $goods_Order)
    {
        $goods_Order->delete();
    }

    public function delBidOrder(Bid_Order $bid_Order)
    {
        $bid_Order->delete();
    }
}
